package com.feng.service.impl;

import com.feng.domain.ResponseResult;
import com.feng.enums.AppHttpCodeEnum;
import com.feng.exception.SystemException;
import com.feng.service.OssUpLoadService;
import com.feng.utils.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class OssUpLoadServiceImpl implements OssUpLoadService {
    @Override
    public ResponseResult upLoad(MultipartFile img) {

        //判断文件类型
        if(!img.getOriginalFilename().endsWith(".jpg") && !img.getOriginalFilename().endsWith(".png")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        //自定义文件目录及名字
        String imgPath = PathUtils.imgPath(img.getOriginalFilename());
        //上传图片并返回地址
        String imgUrl = upLoadOss(img, imgPath);

        return ResponseResult.okResult(imgUrl);
    }

    private String accessKey;
    private String secretKey;
    private String bucket;

    private String upLoadOss(MultipartFile file, String imgPath){
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        String key = imgPath;
        try {
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://rt6003e2p.hb-bkt.clouddn.com/" + key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return null;
    }
}
